import { createStore } from "vuex";
import { getUser } from "@/api/apiv1";
import { login } from "@/api/apiv1";
import { setToken,removeToken } from "@/composables/auth";
import { message } from "@/composables/util";
import { useCookies } from '@vueuse/integrations/useCookies';

const cookie = useCookies()

const store = createStore({
  state() {
    return {
      // 用户信息
      user: {},

      // 侧边宽度
      asideWidth: "250px",

      menus: [],
      ruleNames: [],
      tagList: []
    };
  },
  mutations: {
    // 记录用户信息
    SET_USERINFO(state, user) {
      state.user = user;
    },

    // 展开/缩起
    handleAsideWidth(state){
      state.asideWidth = state.asideWidth == "250px"? "64px":"250px"
    },

    SET_MENUS(state,menus){
      state.menus = menus
    },

    SET_RULENAMES(state,ruleNames){
      state.ruleNames = ruleNames
    }
  },
  actions: {

    // 登录
    login({commit},{username,password}){
        return new Promise((resolve, reject) => {
            login(username,password).then(res=>{
                if(res.code == 200){
                    message("登录成功");
                    setToken(res.data.token);
                    resolve(res)
                }else{
                    message("账号或密码错误","error")
                    reject(res)
                }
            }).catch(err=>reject(err))
        })
    },

    // 获取当前登录用户信息
    getUser({ commit }) {
      return new Promise((resolve, reject) => {
        getUser().then(res => {
            commit("SET_USERINFO",res);
            resolve(res)
        }).catch(err=>{
            // 若获取用户信息出错 先清除cookie中的token
            //logout();
            removeToken();
            commit("SET_USERINFO",{});
            reject(err);
        });
      });
    },

    // 退出登录
    logout( { commit } ){
        // 移除token
        removeToken();
        // 清除当前用户状态
        commit("SET_USERINFO",{});
        // 清除标签信息
        cookie.remove("tabList")
    }
  },
});

export default store;
